using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using UniversalAdminSystem.Infrastructure.Configs;

namespace UniversalAdminSystem.Infrastructure.Auth;

public class JwtTokenBuilder
{
    private readonly JwtConfig _jwtConfig;
    
    public JwtTokenBuilder(IOptions<JwtConfig> options)
    {
        _jwtConfig = options.Value;
    }
    
    public string BuildToken(List<Claim> claims, int? expireHours = null)
    {
        Console.WriteLine($"开始构建JWT Token，Claims数量: {claims.Count}");
        Console.WriteLine($"JWT密钥长度: {_jwtConfig.Key.Length}");
        
        if (string.IsNullOrEmpty(_jwtConfig.Key))
        {
            throw new InvalidOperationException("JWT密钥不能为空");
        }
        
        if (_jwtConfig.Key.Length < 16)
        {
            throw new InvalidOperationException($"JWT密钥长度不足，当前长度: {_jwtConfig.Key.Length}，建议至少16位");
        }
        
        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtConfig.Key));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
        
        var token = new JwtSecurityToken(
            issuer: _jwtConfig.Issuer,
            audience: _jwtConfig.Audience,
            claims: claims,
            expires: DateTime.UtcNow.AddHours(expireHours ?? _jwtConfig.ExpireHours),
            signingCredentials: creds
        );

        var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
        Console.WriteLine($"JWT Token生成成功，长度: {tokenString.Length}");
        
        return tokenString;
    }
} 